import { Project } from "../screens/project-list/list";
import { useHttp } from "./http";
import { QueryKey, useMutation, useQuery, useQueryClient } from "react-query";
import {
    useDeleteConfig,
    useEditConfig,
    useAddConfig,
} from "./use-optimistic-options";

// 获取项目列表
export const useProjects = (param?: Partial<Project>) => {
    const client = useHttp();

    return useQuery<Project[]>(["projects", param], () =>
        client("projects", { data: param })
    );
};

// 编辑某一项目
export const useEditProject = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        (params: Partial<Project>) =>
            client(`projects/${params.id}`, {
                data: params,
                method: "PATCH",
            }),
        useEditConfig(queryKey)
    );
};

// 新增项目
export const useAddProject = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        (params: Partial<Project>) =>
            client(`projects`, {
                data: params,
                method: "POST",
            }),
        useAddConfig(queryKey)
    );
};

// 删除项目
export const useDeleteProject = (queryKey: QueryKey) => {
    const client = useHttp();
    return useMutation(
        ({ id }: { id: number }) =>
            client(`projects/${id}`, {
                method: "DELETE",
            }),
        useDeleteConfig(queryKey)
    );
};

// 获取项目详情
export const useProject = (id?: number) => {
    const client = useHttp();
    return useQuery<Project>(
        ["project", { id }],
        () => client(`projects/${id}`),
        {
            enabled: Boolean(id),
        }
    );
};
